import 'dart:math';

import 'package:cave_flutter/common/common_edit_widget.dart';
import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/utils/whl_current_limiting_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/empty_widget.dart';
import 'package:cave_flutter/widgets/whl_button.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:cave_flutter/utils/extension/datetime_extension.dart';

import '../../../common/list_view_group.dart';
import '../../../model/comment_model.dart';
import '../../../widgets/ruler_widget.dart';

class CommentWidget extends StatefulWidget {
  String dynamicId = "";
  DynamicDataSource? source;

  CommentWidget({Key? key, this.source, required this.dynamicId})
      : super(key: key);

  @override
  State<CommentWidget> createState() => _CommentWidgetState();
}

class _CommentWidgetState extends State<CommentWidget> {
  List<CommentModel> listData = [];
  ListViewGroupHandler? groupHandler;
  TextEditingController editingController = TextEditingController();
  EasyRefreshController refreshController = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);
  int current = 1;
  int size = 10;
  String inputContent = "";
  String voiceUrl = "";
  String replyAccountId = "";
  String replyAccountName = "";
  String replyCommentId = "";
  int total = 0;
  FocusNode focusNode = FocusNode();
  ValueNotifier<bool> isShowEmoji = ValueNotifier<bool>(false);

  @override
  void initState() {
    super.initState();
    loadCommentData(isRefresh: true);
  }

  loadCommentData({bool isRefresh = false, int? customSzie}) {
    if (isRefresh) {
      current = 1;
    } else {
      current++;
    }
    String api = widget.source == DynamicDataSource.Cave
        ? WhlApi.getCaveCommentList
        : WhlApi.getCommentList;
    api.get({
      "current": current,
      "size": customSzie ?? size,
      "squareId": widget.dynamicId
    }).then((value) {
      if (value.isSuccess()) {
        List records = value.data["records"];
        total = value.data['total'];
        List<CommentModel> modelList =
            records.map((e) => CommentModel.fromJson(e)).toList();
        if (isRefresh) {
          listData = modelList;
          refreshController.finishRefresh();
          refreshController.resetFooter();
        } else {
          listData.addAll(modelList);
          refreshController.finishLoad();
        }
        if (records.length < size) {
          refreshController.finishLoad(IndicatorResult.noMore);
        }
        setState(() {});
      } else {
        current--;
        refreshController.finishRefresh();
        refreshController.finishLoad();
        setState(() {});
      }
    });
  }

  addCommentRequest() {
    Map<String, dynamic> param = {
      "squareId": widget.dynamicId,
      "audioUrl": voiceUrl,
      "content": inputContent,
      "anonymous": 0
    };

    String api = widget.source == DynamicDataSource.Cave
        ? WhlApi.addCaveComment
        : WhlApi.addComment;
    api.post(param).then((value) {
      if (value.isSuccess()) {
        editingController.text = "";
        loadCommentData(isRefresh: true, customSzie: current * size);
      }
    });
  }

  replyCommentRequest() {
    Map<String, dynamic> param = {
      "targetAccountId": replyAccountId,
      "squareId": widget.dynamicId,
      "commentId": replyCommentId,
      "content": inputContent
    };

    String api = widget.source == DynamicDataSource.Cave
        ? WhlApi.replyCaveComment
        : WhlApi.replyComment;
    api.post(param).then((value) {
      isShowEmoji.value = false;

      if (value.isSuccess()) {
        editingController.text = "";
        loadCommentData(isRefresh: true, customSzie: current * size);
      }
    });
  }

  loveCommentRequest(CommentModel commentModel) {
    Map<String, dynamic> param = {"id": commentModel.id};
    String api = widget.source == DynamicDataSource.Cave
        ? WhlApi.commentCaveDianzan
        : WhlApi.commentDianzan;
    api.post(param).then((value) {
      isShowEmoji.value = false;
      if (value.isSuccess()) {
        setState(() {
          commentModel.isGood = true;
        });
      }
    });
  }

  doClickEmoji() {
    isShowEmoji.value = !isShowEmoji.value;
  }

  @override
  Widget build(BuildContext context) {
    groupHandler = getGroupHandler();
    return Container(
      constraints: BoxConstraints(maxHeight: ScreenUtil().screenHeight - 250.h),
      child: UIColumn(
        topLeftRadius: 30.w,
        topRightRadius: 30.w,
        color: kAppWhiteColor,
        children: [
          IntrinsicHeight(
            child: UIRow(
              padding: EdgeInsets.symmetric(horizontal: 14.w),
              margin: EdgeInsets.only(top: 19.h),
              children: [
                if (total > 0)
                  Expanded(
                    child: UIText(
                      margin: EdgeInsets.only(left: 30.w),
                      text: '$total条评论',
                      alignment: Alignment.center,
                      fontSize: 13.sp,
                      textColor: kAppBlackColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                const Spacer(),
                UIContainer(
                  padding: EdgeInsets.all(5.w),
                  child: UIImage(
                    padding: EdgeInsets.all(2.w),
                    assetImage: "icon_voice_close",
                    color: kAppColor("#DCDCDC"),
                    radius: 10.w,
                    width: 20.w,
                    height: 20.w,
                    onTap: () {
                      Get.back(result: {'commentNum': listData.length});
                    },
                  ),
                )
              ],
            ),
          ),
          if (total == 0)
            Expanded(
              child: Column(
                children: [
                  UIImage(
                    assetImage: 'mine_noData.png',
                    margin: EdgeInsets.only(top: 50.h),
                  ),
                  UIText(
                    text: '暂无任何评论',
                    margin: EdgeInsets.only(bottom: 4.h, top: 10.h),
                  ),
                  UIText(
                    text: '快留下你的精彩评论吧',
                    textColor: kAppColor('#BEBEBE'),
                    margin: EdgeInsets.only(bottom: 50.h),
                  ),
                  UISolidButton(
                    width: 133.w,
                    text: '去评论',
                    color: kAppColor('#F5F7F9'),
                    textColor: kAppColor('#000000'),
                    onTap: () {
                      focusNode.requestFocus();
                    },
                  )
                ],
              ),
            )
          else
            Expanded(child: getCommentListView()),
          UIRow(
            margin: EdgeInsets.symmetric(horizontal: 18.w, vertical: 13.h),
            padding: EdgeInsets.only(left: 17.w, right: 21.w),
            color: kAppColor("#F4F5F8"),
            radius: 22.h,
            height: 44.h,
            children: [
              Expanded(
                child: TextField(
                  focusNode: focusNode,
                  onChanged: (value) {},
                  onEditingComplete: () {},
                  onSubmitted: (text) {
                    if (text.isEmpty) {
                      MyToast.show("请输入评论内容");
                      return;
                    }
                    inputContent = text;
                    FocusScope.of(Get.context!).requestFocus(FocusNode());
                    if (replyAccountId.isNotEmpty) {
                      replyCommentRequest();
                    } else {
                      addCommentRequest();
                    }
                  },
                  controller: editingController,
                  textInputAction: TextInputAction.send,
                  style: TextStyle(fontSize: 14.sp, color: kAppSubTextColor),
                  decoration: InputDecoration(
                    counterText: "",
                    border: InputBorder.none,
                    hintText: replyAccountName.isNotEmpty
                        ? '回复$replyAccountName…'
                        : "输入消息…",
                    hintStyle:
                        TextStyle(fontSize: 14.sp, color: kAppSub3TextColor),
                  ),
                ),
              ),
              // UIImage(
              //   assetImage: "icon_chat_record.png",
              //   width: 30.w,
              //   height: 30.w,
              // ),
              UIImage(
                assetImage: "icon_chat_emoji.png",
                width: 30.w,
                height: 30.w,
                onTap: () {
                  doClickEmoji();
                },
              ),
              // UIImage(
              //   assetImage: "dynamic_at.png",
              //   width: 30.w,
              //   height: 30.w,
              // )
            ],
          ),
          ValueListenableBuilder<bool>(
            valueListenable: isShowEmoji,
            builder: (context, bool isShow, Widget? child) {
              return Visibility(
                visible: isShow,
                child: SizedBox(
                  height: 200.h,
                  child: Stack(
                    alignment: Alignment.bottomRight,
                    children: [
                      EmojiPicker(
                        onEmojiSelected: (category, emoji) {
                          editingController.text =
                              editingController.text + emoji.emoji;
                        },
                        onBackspacePressed: () {
                          if (editingController.text.isEmpty) return;
                          WhlCurrentLimitingUtil.debounce(() {
                            editingController.text = editingController.text
                                .substring(
                                    0,
                                    min(editingController.text.length - 2,
                                        editingController.text.length - 1));
                          });
                        },
                        config: Config(
                            columns: 7,
                            emojiSizeMax: 25.w,
                            verticalSpacing: 0,
                            horizontalSpacing: 0,
                            initCategory: Category.RECENT,
                            bgColor: kAppColor('#FDFDFD'),
                            indicatorColor: Colors.blue,
                            iconColor: Colors.grey,
                            iconColorSelected: Colors.blue,
                            recentsLimit: 28,
                            categoryIcons: const CategoryIcons(),
                            buttonMode: ButtonMode.MATERIAL),
                      ),
                      UIText(
                        margin: EdgeInsets.only(bottom: 20.h, right: 20.w),
                        text: '发送',
                        fontSize: 16.sp,
                        textColor: Colors.white,
                        alignment: Alignment.center,
                        width: 60.w,
                        height: 30.h,
                        radius: 4.w,
                        gradientStartColor: kAppLeftColor,
                        gradientEndColor: kAppRightColor,
                        onTap: () {
                          String text = editingController.text;
                          if (text.isEmpty) {
                            MyToast.show("请输入评论内容");
                            return;
                          }
                          inputContent = text;
                          FocusScope.of(Get.context!).requestFocus(FocusNode());
                          if (replyAccountId.isNotEmpty) {
                            replyCommentRequest();
                          } else {
                            addCommentRequest();
                          }
                        },
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget getCommentListView() {
    return ListView.builder(
      itemBuilder: (context, index) {
        return groupHandler!.cellAtIndex(index);
      },
      itemCount: groupHandler!.allItemCount,
      shrinkWrap: true,
    );
  }

  ListViewGroupHandler getGroupHandler() {
    return ListViewGroupHandler(
      numberOfSections: listData.length,
      numberOfRowsInSection: (int section) {
        CommentModel commentModel = listData[section];
        if (commentModel.isShow == true) {
          return commentModel.messages?.length ?? 0;
        }
        return min(commentModel.messages?.length ?? 0, 3);
      },
      headerForSection: (section) {
        CommentModel commentModel = listData[section];
        return getCommentSectionWidget(commentModel);
      },
      footerForSection: (section) {
        CommentModel commentModel = listData[section];
        // 展开3条回复
        if (commentModel.isShow != true &&
            (commentModel.messages?.length ?? 0) > 3) {
          return UIText(
            margin: EdgeInsets.only(left: 62.w, right: 42.w, top: 6.h),
            text: '展开${(commentModel.messages?.length ?? 0) - 3}条回复',
            textColor: kAppColor("#21415F"),
            fontSize: 13.sp,
            onTap: () {
              setState(() {
                commentModel.isShow = true;
              });
            },
          );
        }
        return UIContainer();
      },
      cellForRowAtIndexPath: (IndexPath indexPath) {
        CommentModel commentModel = listData[indexPath.section];
        ReplyCommentModel model = commentModel.messages![indexPath.row];
        return getCommentWidget(model);
      },
    );
  }

  Widget getCommentSectionWidget(CommentModel commentModel) {
    return UIColumn(
      padding: EdgeInsets.only(left: 20.w, right: 16.w, top: 22.h),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        UIRow(
          children: [
            UIImage(
              httpImage: commentModel.avatar?.toImageUrl(),
              assetPlaceHolder: WHLGlobalConfig.userPlaceholderAvatar,
              width: 34.w,
              height: 34.w,
              radius: 17.w,
            ),
            Expanded(
                child: UIText(
              margin: EdgeInsets.symmetric(horizontal: 5.w),
              text: commentModel.nickName,
              fontSize: 14.sp,
              textColor: kAppSub3TextColor,
              overflow: TextOverflow.ellipsis,
              shrinkWrap: false,
            )),
            UIText(
              text: '${commentModel.goodNum}',
              textColor: kAppColor('#817F7F'),
              fontSize: 11.sp,
              marginDrawable: 3.w,
              startDrawable: UIImage(
                assetImage: commentModel.isGood == true
                    ? 'dynamic_love'
                    : 'dynamic_unLove.png',
                width: 18.w,
              ),
              onTap: () {
                loveCommentRequest(commentModel);
              },
            )
          ],
        ),
        UIContainer(
          margin: EdgeInsets.only(top: 3.h, left: 28.w, right: 16.w),
          child: Text(
            commentModel.content ?? "",
            style: TextStyle(
              fontSize: 14.sp,
              color: kAppSubTextColor,
            ),
          ),
        ),
        UIRow(
          margin: EdgeInsets.only(top: 7.h, left: 28.w, right: 16.w),
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            UIText(
              text: (commentModel.pubTime ?? "").isNotEmpty
                  ? DateTime.parse(commentModel.pubTime!)
                      .formatTodayTimeStr(isDetail: true)
                  : "",
              textColor: kAppSub3TextColor,
              fontSize: 12.sp,
            ),
            UIText(
              padding: EdgeInsets.only(left: 3.w, right: 10.w),
              text: "回复",
              textColor: kAppColor("#21415F"),
              fontSize: 12.sp,
              onTap: () {
                replyCommentId = commentModel.id ?? "";
                replyAccountId = commentModel.accountId ?? "";
                replyAccountName = commentModel.nickName ?? "";
                setState(() {});
              },
            )
          ],
        )
      ],
    );
  }

  Widget getCommentWidget(ReplyCommentModel model) {
    return UIColumn(
      padding: EdgeInsets.only(left: 62.w, right: 42.w),
      margin: EdgeInsets.only(top: 3.h),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        UIContainer(
          margin: EdgeInsets.only(top: 7.h),
          child: Text.rich(
            TextSpan(
                text: model.sourceNickName,
                style: TextStyle(fontSize: 14.sp, color: kAppSub3TextColor),
                children: [
                  TextSpan(
                    text: " 回复 ",
                    style: TextStyle(fontSize: 14.sp, color: kAppSubTextColor),
                  ),
                  TextSpan(
                    text: "${model.targetNickName}：",
                    style: TextStyle(fontSize: 14.sp, color: kAppSub3TextColor),
                  ),
                  TextSpan(
                    text: model.content,
                    style: TextStyle(fontSize: 14.sp, color: kAppSubTextColor),
                  )
                ]),
          ),
        ),
        UIRow(
          margin: EdgeInsets.only(top: 3.h),
          children: [
            UIText(
              text: (model.pubTime ?? "").isNotEmpty
                  ? DateTime.parse(model.pubTime!)
                      .formatTodayTimeStr(isDetail: true)
                  : "",
              textColor: kAppSub3TextColor,
              fontSize: 12.sp,
            ),
            UIText(
              padding: EdgeInsets.only(left: 3.w, right: 10.w),
              text: "回复",
              textColor: kAppColor("#21415F"),
              fontSize: 12.sp,
              onTap: () {
                replyCommentId = model.commentId ?? "";
                replyAccountId = model.sourceAccountId ?? "";
                replyAccountName = model.sourceNickName ?? "";
                setState(() {});
              },
            )
          ],
        )
      ],
    );
  }
}
